<template>
  <div class="food-container">
    <el-card class="search-card" shadow="hover">
      <!-- 搜索框部分 -->
      <div class="search-header">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索食物..."
          :prefix-icon="Search"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button type="primary" :loading="loading" @click="handleSearch">
              搜索
            </el-button>
          </template>
        </el-input>
      </div>

      <!-- 搜索历史部分 -->
      <div v-if="!searchKeyword && searchHistory.length" class="search-suggestions">
        <div class="section-header">
          <h4>最近搜索</h4>
          <el-button type="text" @click="clearHistory">
            清空历史
          </el-button>
        </div>

        <div class="history-tags">
          <el-tag
            v-for="item in searchHistory"
            :key="item"
            class="history-tag"
            @click="searchKeyword = item"
          >
            {{ item }}
          </el-tag>
        </div>
      </div>

      <!-- 搜索结果部分 -->
      <div v-if="searchKeyword" class="search-results">
        <el-table
          v-loading="loading"
          :data="searchResults"
          style="width: 100%"
        >
          <el-table-column prop="name" label="食物名称">
            <template #default="{ row }">
              <div class="food-name-cell">
                <el-image
                  :src="row.image"
                  class="food-thumbnail"
                  fit="cover"
                >
                  <template #error>
                    <div class="image-placeholder">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
                <span>{{ row.name }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="category" label="分类" width="120" />
          
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-checkbox
                :value="row.id"
                v-model="selectedFoods"
                @change="handleSelect(row)"
              >
                选择
              </el-checkbox>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 食物详情对话框... -->
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { useStore } from 'vuex'

const store = useStore()
const loading = ref(false)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

// 从 store 获取数据
const searchResults = computed(() => store.state.food.searchResults || [])
const searchHistory = computed(() => store.state.food.searchHistory || [])
const total = computed(() => store.state.food.total || 0)

// 搜索处理
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }

  try {
    loading.value = true
    await store.dispatch('food/searchFood', {
      keyword: searchKeyword.value,
      page: currentPage.value,
      pageSize: pageSize.value
    })
  } catch (error) {
    ElMessage.error('搜索失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 初始化
onMounted(async () => {
  try {
    loading.value = true
    await Promise.all([
      store.dispatch('food/getSearchHistory'),
      store.dispatch('food/getFoodCategories')
    ])
  } catch (error) {
    console.error('初始化失败:', error)
    ElMessage.error('获取数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
})

// 清空搜索历史
const clearHistory = async () => {
  try {
    await store.dispatch('food/clearSearchHistory')
    ElMessage.success('搜索历史已清空')
  } catch (error) {
    ElMessage.error('清空失败，请稍后重试')
  }
}

const selectedFoods = ref([])

const handleSelect = (food) => {
  // 如果选中，添加到已选列表
  if (selectedFoods.value.includes(food.id)) {
    store.commit('food/ADD_SELECTED_FOOD', food)
    ElMessage.success(`已添加 ${food.name}`)
  } else {
    // 如果取消选中，从已选列表移除
    store.commit('food/REMOVE_SELECTED_FOOD', food.id)
    ElMessage.info(`已移除 ${food.name}`)
  }
}

// ... 其他方法
</script>

<style lang="scss" scoped>
.food-container {
  padding: 20px;

  .search-card {
    .search-header {
      margin-bottom: 20px;
    }

    .search-suggestions {
      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;

        h4 {
          margin: 0;
          font-size: 16px;
          color: var(--el-text-color-primary);
        }
      }

      .history-tags {
        margin-bottom: 24px;

        .history-tag {
          margin: 0 8px 8px 0;
          cursor: pointer;
        }
      }

      .food-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        gap: 20px;
        margin-top: 16px;

        .food-card {
          cursor: pointer;

          .food-image {
            height: 150px;
            overflow: hidden;

            .el-image {
              width: 100%;
              height: 100%;
            }

            .image-placeholder {
              height: 100%;
              display: flex;
              justify-content: center;
              align-items: center;
              background-color: var(--el-fill-color-light);

              .el-icon {
                font-size: 40px;
                color: var(--el-text-color-secondary);
              }
            }
          }

          .food-info {
            padding: 12px;

            h3 {
              margin: 0 0 8px;
              font-size: 16px;
              color: var(--el-text-color-primary);
            }

            .nutrition-info {
              color: var(--el-text-color-secondary);
              font-size: 14px;
            }
          }
        }
      }
    }

    .search-results {
      .food-name-cell {
        display: flex;
        align-items: center;
        gap: 12px;

        .food-thumbnail {
          width: 40px;
          height: 40px;
          border-radius: 4px;
        }
      }
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
  }
}

.food-detail {
  .detail-header {
    display: flex;
    gap: 24px;

    .food-image {
      width: 200px;
      height: 200px;
      border-radius: 8px;
    }

    .basic-info {
      flex: 1;

      h2 {
        margin: 0 0 12px;
      }

      p {
        margin: 0 0 20px;
        color: var(--el-text-color-secondary);
      }

      .actions {
        display: flex;
        gap: 12px;
      }
    }
  }

  .nutrition-detail {
    margin: 24px 0;

    h3 {
      margin: 0 0 16px;
    }
  }

  .food-tips {
    margin-top: 24px;

    h3 {
      margin: 0 0 16px;
    }

    .tip-item {
      margin-bottom: 8px;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

.unit {
  margin-left: 8px;
  color: var(--el-text-color-secondary);
}
</style> 